package all.com.jinyongqunxiax.modules.modlist;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.randy.fundation.FileUtils;
import com.randy.fundation.JxFunc;
import com.randy.fundation.Logger;

import net.idik.lib.slimadapter.SlimAdapter;
import net.idik.lib.slimadapter.SlimInjector;
import net.idik.lib.slimadapter.viewinjector.IViewInjector;

import org.apache.commons.io.FilenameUtils;

import java.util.ArrayList;
import java.util.List;

import all.com.jinyongqunxiax.R;
import all.com.jinyongqunxiax.modules.ModDetailActivity;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import jy.game.components.mod.JyModInfo;
import jy.game.tools.BasePojoManager;
import jy.game.tools.JyResourceManager;
import lib.folderpicker.FolderPicker;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class ModListActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {
    static final int RC_GET_MOD_ROOT        = 1;
    static final int RC_CAMERA_AND_LOCATION = 2;


    String          modRoot    = Environment.getExternalStorageDirectory().getPath() + "/Android/data/com.wanqianqunxia.mod/files/modcache";
    List<ViewModel> viewModels = new ArrayList<>(10);
    SlimAdapter     adapter    = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
        setTitle("Mods");


        SharedPreferences pref = getApplicationContext().getSharedPreferences("settings", MODE_PRIVATE);
        modRoot = pref.getString("mod-root", modRoot);

        RecyclerView recyclerView = findViewById(R.id.main_mod_listview);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));


        adapter = SlimAdapter.create().register(R.layout.main_mod_item, new SlimInjector<ViewModel>() {
                @Override public void onInject(ViewModel viewModel, IViewInjector injector) {
                    injector.text(R.id.main_mod_item_title, viewModel.title);
                    injector.clicked(R.id.main_mod_item_title, v -> {
                        Intent intent = ModDetailActivity.Options.intent(ModListActivity.this, viewModel.title,
                            FilenameUtils.concat(modRoot, viewModel.title));
                        ModListActivity.this.startActivity(intent);
                    });
                }
            }
        ).attachTo(recyclerView);

        String[] perms = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE};
        if (!EasyPermissions.hasPermissions(this, perms)) {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, "给我吧",
                RC_CAMERA_AND_LOCATION, perms);

        } else {
            loadNewData();
        }
    }


    void loadNewData() {
        FileUtils.walk(modRoot, (dir, name) -> name.endsWith("xml"), file -> {
            BasePojoManager<JyModInfo> manager = BasePojoManager.build(file, JyModInfo.class);
            JxFunc.of(manager).ifPresent(value -> JxFunc.of(value.datas).ifPresent(data -> {
                JyResourceManager.add(JyModInfo.class, data.name, data);
                viewModels.add(new ViewModel(data));
            }));
        });
        adapter.updateData(viewModels);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.set_mod_path:
                Intent intent = new Intent(this, FolderPicker.class);
                intent.putExtra("title", "选择mod所在目录");
                String androidDataDir = Environment.getExternalStorageDirectory().getPath() + "/Android/data";
                intent.putExtra("location", TextUtils.isEmpty(modRoot) ? androidDataDir : modRoot);
                intent.putExtra("pickFiles", false);
                startActivityForResult(intent, RC_GET_MOD_ROOT);
                break;
            default:
                Logger.d("Not handle %d", id);
                break;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            Logger.d("request#%d canceled. %d", requestCode, requestCode);
            return;
        }

        if (requestCode == RC_GET_MOD_ROOT) {
            if (data == null || data.getExtras() == null) {
                Logger.d("invalid result");
                return;
            }

            String root = data.getExtras().getString("data");
            Logger.d("mod root: %s", root);

            if (TextUtils.isEmpty(modRoot)) {
                Toast.makeText(this, "mod root: empty", Toast.LENGTH_LONG).show();
                return;
            }

            modRoot = root;

            SharedPreferences        pref   = getApplicationContext().getSharedPreferences("settings", MODE_PRIVATE);
            SharedPreferences.Editor editor = pref.edit();
            editor.putString("mod-root", modRoot);
            editor.apply();

            loadNewData();

            Toast.makeText(this, "mod root:" + root, Toast.LENGTH_LONG).show();
        } else if (requestCode == RC_CAMERA_AND_LOCATION) {

        } else if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
            Toast.makeText(this, "设置了吗", Toast.LENGTH_LONG)
                .show();
        } else {
            Logger.d("Not handle %d", requestCode);
        }

        //TODO handle your request here
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> list) {
        loadNewData();
        adapter.updateData(viewModels);
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    private static class ViewModel {
        public  String    title;
        private JyModInfo model;

        ViewModel(JyModInfo model) {
            this.model = model;
            this.title = model.name;
        }
    }
}
